package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author wangqian
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadlocal = new ThreadLocal<OrderSubmitVo>();
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 给订单确认页返回需要用的数据
     *
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo vo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1、主线程获取数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //2、将主线程获取的数据分享到副线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //远程调用查询当前用户的所有收货地址；
            List<MemberAddressVo> addressVoList = memberFeignService.getAddress(memberRespVo.getId());
            vo.setAddressVos(addressVoList);
        }, executor);

        CompletableFuture<Void> getUserCartItems = CompletableFuture.runAsync(() -> {
            //远程查询获取当前用户的所有购物项目
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> orderItemVos = cartFeignService.getCurrentUserCartItems();
            vo.setItemVos(orderItemVos);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = vo.getItemVos();
            List<Long> stockNum = items.stream().map(item->item.getSkuId()).collect(Collectors.toList());
            //todo 调用远程方法查询库存信息
//            R hasStock = wmsFeignService.getSkuHasStock(stockNum);
//            List<SkuStockVo> skuStockVos = hasStock.getData(new TypeReference<List<SkuStockVo>>(){});
//            if(skuStockVos!=null){
//                Map<Long, Boolean> map = skuStockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId,SkuStockVo::getHasStock));
//                vo.setStocks(map);
//            }
        }, executor);

        Integer integration = memberRespVo.getIntegration();
        vo.setIntegration(integration);

        //todo 5、防重令牌
        //生成token
        String token = UUID.randomUUID().toString().replace("-","");
        //向页面传递
        vo.setOrderToken(token);
        //在服务器中保存，以备后续调用
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        CompletableFuture.allOf(getAddressFuture, getUserCartItems).get();
        return vo;
    }

    /**
     * 下单功能
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadlocal.set(vo);
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //创建订单，验令牌 验价格 锁库存 下单成功，来到支付选择页、、 下单失败，回到订单确认页重新确认订单信息

        responseVo.setCode(0);

        //1、验证令牌
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1])" +
                "else return 0 end";
        //删除锁
        String orderToken = vo.getOrderToken();
        //这个脚本最终返回0：令牌校验失败和1：令牌校验成功
        Long lockResult = (Long) redisTemplate.execute(new DefaultRedisScript(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId()),orderToken);
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId());
//        //令牌的验证、删除必须保证原子性，则直接用脚本来执行
//        if(redisToken!=null&&redisToken.equals(orderToken)){
//            //令牌验证通过
//        }else{
//            //令牌验证不通过
//            responseVo.setCode(1);
//            return responseVo;
//        }
        if(lockResult==0L){
            //令牌验证失败被
            responseVo.setCode(1);
            return responseVo;
        }else{
            //原子验证令牌和删除令牌成功
            //1、开始创建订单并完善订单的信息
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){

                //3、保存订单
                saveOrder(order);
                //4、锁定库存,只要出现异常，回滚所有订单数据
                //订单号，所有订单项目（skuId,skuName,num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getOrderItems().stream().map(item->{
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(orderItemVos);
                //todo 远程锁定库存方法
                R r = wmsFeignService.orderLockStock(lockVo);
                if(r.getCode()==0){
                    //库存锁定成功
                    responseVo.setOrder(order.getOrder());
                    return responseVo;
                }else{
                    //库存锁定失败
                    responseVo.setCode(3);
                    return responseVo;
                }
            }else{
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    /**
     * 保存订单数据
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        orderEntity.setMemberId(memberRespVo.getId());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder(){

        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1、生成一个订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = createOrder(orderSn);
        //2、获取所有的订单项目

        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        //3 验价(计算价格相关)
        computePrice(orderEntity,orderItemEntities);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);
        return orderCreateTo;

    }

    /**
     * 验价方法
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal giftIntegration = new BigDecimal("0.0");
        BigDecimal giftGrowth = new BigDecimal("0.0");
        for(OrderItemEntity entity:orderItemEntities){
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            giftIntegration = giftIntegration.add(new BigDecimal(entity.getGiftIntegration().toString()));
            giftGrowth = giftGrowth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        //设置应付总额（订单价格+运费）
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        //设置积分等信息
        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());

        //删除状态(0:未删除 1:已删除)
        orderEntity.setDeleteStatus(0);
    }

    /**
     * 根据指定订单号构建一个订单
     * @param orderSn
     */
    private OrderEntity createOrder(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadlocal.get();
        R fares = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = fares.getData(new TypeReference<FareVo>(){});
        //设置运费信息
        orderEntity.setFreightAmount(fareVo.getFare());
        //设置其他收获项信息
        orderEntity.setReceiverCity(fareVo.getAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getAddressVo().getDetailAddress());
        orderEntity.setReceiverPostCode(fareVo.getAddressVo().getPostCode());
        orderEntity.setReceiverName(fareVo.getAddressVo().getName());
        orderEntity.setReceiverPhone(fareVo.getAddressVo().getPhone());
        orderEntity.setReceiverProvince(fareVo.getAddressVo().getProvince());
        orderEntity.setReceiverRegion(fareVo.getAddressVo().getRegion());

        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);


        return orderEntity;
    }

    /**
     * 构建多个订单项数据
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每次购物项目的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        List<OrderItemEntity> list = null;
        if(currentUserCartItems!=null&&currentUserCartItems.size()>0) {
            list = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return list;
    }
    /**
     * 构建每一个（某一个指定的订单项）订单项数据
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息、订单号
        //2、商品的SPU信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>(){});
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
//        orderItemEntity.setSpuPic(spuinfo);
        //3、商品的SKU信息
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(),";"));
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4、商品优惠信息（不做）
        //5、积分信息
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        //6、订单项目的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        //当前订单项目的实际金额（总价X数量-优惠金额）
        BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        orderItemEntity.setRealAmount(orign.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount())
                .subtract(orderItemEntity.getCouponAmount()));
        return null;
    }
}